package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.ConceptoMovimiento;
import com.ingenio.business.TipoMovimiento;
import com.ingenio.dao.ConceptoMovimientoAdapter;
import com.ingenio.dao.TipoMovimientoAdapter;

/**
 * Servlet implementation class DevolverConceptosMovimientosServlet
 */
@WebServlet("/DevolverConceptos")
public class DevolverConceptosMovimientosServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverConceptosMovimientosServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer idTipoMov = Integer.parseInt(request.getParameter("idTipoMovimiento"));
		TipoMovimientoAdapter tma = new TipoMovimientoAdapter();
		ConceptoMovimientoAdapter cma = new ConceptoMovimientoAdapter();
		JSONObject json = new JSONObject();
		try {
			TipoMovimiento tm = tma.devolverTipoMovimiento(idTipoMov);
			if (tm != null){
				JSONArray ja = new JSONArray();
				List<ConceptoMovimiento> conceptos = cma.devolverConceptosTipoMov(tm);
				for (ConceptoMovimiento cm: conceptos){
					JSONObject jconcepto = new JSONObject();
					jconcepto.put("idConcepto",cm.getIdConcepto());
					jconcepto.put("descConcepto",cm.getDescConcepto());
					ja.put(jconcepto);
				}
				json.put("conceptos", ja);
			}else{
				json.put("error",true);
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


